/*
 * Copyright 2025 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sychip.fhc

import android.app.PendingIntent
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.nfc.NdefRecord
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.Ndef
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.compose.ui.platform.LocalContext
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.view.WindowCompat
import androidx.lifecycle.lifecycleScope
import com.fhc.base.CRASH_INFO
import com.fhc.base.EventType
import com.fhc.base.FhcFlowEventBus
import com.fhc.base.FlowEventBusData
import com.fhc.base.LocalManager.LanguageProvider
import com.fhc.base.isTablet
import com.fhc.usb.UsbDeviceListener
import com.fhc.usb.UsbDeviceReceiver
import com.sychip.fhc.app.accontrol.AcControl
import com.sychip.fhc.app.drawer.nav.DrawerNavHost
import com.sychip.fhc.app.todo.R
import com.sychip.fhc.app.todo.TodoNavGraph
import com.sychip.fhc.app.wsn.nav.WsnMainTabNavHost
import com.sychip.fhc.base.BaseAppViewModel
import com.sychip.fhc.di.AcitivtyDataManager
import com.sychip.fhc.lib.base.setStatusBarTextColor
import com.sychip.fhc.style.FhcAppTheme
import dagger.hilt.android.AndroidEntryPoint
import jakarta.inject.Inject
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import timber.log.Timber
import kotlin.system.exitProcess

@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    @Inject
    lateinit var appManager: AcitivtyDataManager

    private val baseAppViewModel: BaseAppViewModel by viewModels()
    private var nfcAdapter: NfcAdapter? = null

    private var usbDeviceReceiver: UsbDeviceReceiver? = null

    @RequiresApi(Build.VERSION_CODES.S)
    override fun onCreate(savedInstanceState: Bundle?) {
        enableEdgeToEdge()
        window.isNavigationBarContrastEnforced = false
        WindowCompat.setDecorFitsSystemWindows(window, false) // 沉浸式关键设置
        setStatusBarTextColor(true)
        super.onCreate(savedInstanceState)
//        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        actionBar?.hide()
        val crashInfo = intent.getStringExtra(CRASH_INFO)
        if (crashInfo != null && crashInfo.isNotEmpty()) {
            Toast.makeText(applicationContext, crashInfo, Toast.LENGTH_LONG).show()
        }

        installSplashScreen()
        lifecycleScope.launch {
            APP.TYPE = baseAppViewModel.getAppType()
            setContent {
                FhcAppTheme {
                    val ctx = LocalContext.current
                    if (APP.TYPE == AppType.WSN) {
                        LanguageProvider {
                            var pressedTime: Long = 0
                            WsnMainTabNavHost(onBack = {
                                if (pressedTime + 2000 > System.currentTimeMillis()) {
                                    exitProcess(0)
                                } else {
                                    Toast.makeText(ctx, R.string.pressBackExit, Toast.LENGTH_SHORT).show()
                                }
                                pressedTime = System.currentTimeMillis()
                            })
                        }
                    } else if (APP.TYPE == AppType.DRAWER) {
                        var pressedTime: Long = 0
                        DrawerNavHost(onBack = {
                            if (pressedTime + 2000 > System.currentTimeMillis()) {
                                exitProcess(0)
                            } else {
                                Toast.makeText(ctx, R.string.pressBackExit, Toast.LENGTH_SHORT).show()
                            }
                            pressedTime = System.currentTimeMillis()
                        })
                    } else if (APP.TYPE == AppType.AcControl) {
                        AcControl()
                    } else {
                        TodoNavGraph()
                    }
                }
            }

            setTitle(R.string.app_name)
            if (APP.TYPE == AppType.BleNFC) {
                nfcAdapter = NfcAdapter.getDefaultAdapter(this@MainActivity)
                processNdefTag(intent)
            } else if (APP.TYPE == AppType.WSN) {
//                Timber.e(">>>          usbDeviceReceiver  registerReceiver")
                usbDeviceReceiver?.let {
                    unregisterReceiver(usbDeviceReceiver)
                    usbDeviceReceiver = null
                }
                usbDeviceReceiver = UsbDeviceReceiver(object : UsbDeviceListener {
                    override fun onUsbDeviceAttached(device: UsbDevice) {

                        FhcFlowEventBus.publish(FlowEventBusData(dataType = EventType.UsbAttached))
                    }

                    override fun onUsbDeviceDetached(device: UsbDevice) {
                        FhcFlowEventBus.publish(FlowEventBusData(dataType = EventType.UsbDetached))
                    }
                })
                val filter = IntentFilter().apply {
                    addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
                    addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
                }
                registerReceiver(usbDeviceReceiver, filter)
            }

            if (savedInstanceState == null) {
                appManager.saveThemeMode(lifecycleScope, true)
//            appManager.showToast(lifecycleScope, "设置已保存222222222222222222")
            }
            if (!isTablet()) {
                val remindNotTablet = baseAppViewModel.remindNotTablet()
                if (remindNotTablet) {
                    Toast.makeText(this@MainActivity, getString(R.string.wsn_w_app_for_tablet), Toast.LENGTH_LONG).show()
                }
                baseAppViewModel.setRemindNotTablet(false)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (APP.TYPE == AppType.BleNFC) {
            Timber.i(">>>onResume nfcAdapter ${intent.action}  nfcAdapter: ${nfcAdapter == null}")
            nfcAdapter?.let {
                val intent = Intent(this, javaClass).apply {
                    addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
                }
                val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE)
                val filter = IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)
                filter.addDataType("*/*")
                val filters = arrayOf(
                    filter,
                    IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED),
                    IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED)
                )
                it.enableForegroundDispatch(this, pendingIntent, filters, null)
            }
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        Timber.e(">>>onNewIntent  ${intent.action}")
        if (APP.TYPE == AppType.BleNFC) {
            if (NfcAdapter.ACTION_NDEF_DISCOVERED == intent.action ||
                NfcAdapter.ACTION_TECH_DISCOVERED == intent.action ||
                NfcAdapter.ACTION_TAG_DISCOVERED == intent.action
            ) {
                processNdefTag(intent)
            }
        } else if (APP.TYPE == AppType.WSN) {
            FhcFlowEventBus.publish(FlowEventBusData(dataType = EventType.UsbAttached))
//            unregisterReceiver(usbDeviceReceiver)
//            //app运行中，插入USB
//            usbDeviceReceiver = UsbDeviceReceiver(object : UsbDeviceListener {
//                override fun onUsbDeviceAttached(device: UsbDevice) {
//                    FhcFlowEventBus.publish(FlowEventBusData(dataType = EventType.UsbAttached))
//                }
//                override fun onUsbDeviceDetached(device: UsbDevice) {
//                    FhcFlowEventBus.publish(FlowEventBusData(dataType = EventType.UsbDetached ))
//                }
//            })
//            val filter = IntentFilter().apply {
//                addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
//                addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
//            }
//            registerReceiver(usbDeviceReceiver, filter)
        }
    }

    private fun processNdefTag(intent: Intent) {
//        val aa = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)
//        Timber.i(">>>EXTRA_NDEF_MESSAGES    ${intent.action} ${aa}   ")
        val tag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getParcelableExtra(NfcAdapter.EXTRA_TAG, Tag::class.java)
        } else {
            @Suppress("DEPRECATION")
            intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)
        }

        Timber.i(">>>processNdefTag  ${intent.action}  ${tag == null}   ")
        tag?.let {
//            appViewModel.updateBleNFCConnected(0)
            val ndef = Ndef.get(tag)
            if (ndef != null) {
                val ndefMessage = ndef.cachedNdefMessage
                for (record in ndefMessage.records) {
                    Timber.i("------  ${record.tnf}   ${String(record.type)}    ${String(record.payload)} ")
                    val payload = record.payload
                    if (record.tnf == NdefRecord.TNF_MIME_MEDIA) {
                        if (String(record.type) == "application/vnd.com.fhc.app.mac") {
                            val mac = String(record.payload)
                            Timber.i("11111>>> mac:  $mac ")
//                            val device: ServerDevice = MockServerDevice(name = "" ,address= "00:80:E1:27:FD:4F")
//                            appViewModel.connect(BleScanResults(device))

//                            appViewModel.connect(mac, "AICamera")
                        }
                    } else if (record.tnf == NdefRecord.TNF_WELL_KNOWN) {
//                        if(String(record.type) == "U" ){
//                            val uri = String(payload.sliceArray(1 until payload.size), Charsets.UTF_8)
//                            Timber.i("222222>>>  URI:  $uri ")
//                        }
                        val mac = String(payload.sliceArray(1 until payload.size), Charsets.UTF_8)
                        Timber.i("222222>>>  TNF_WELL_KNOWN:   ${String(record.type)} $mac ")

                        runBlocking {
                            delay(100)
//                            appViewModel.connect(mac, "AICamera")
                        }
                        break
                    } else {
                        Timber.i("333333>>>  URI:  ${String(record.payload)} ")
                    }
//                    Timber.i("readNdefMessage tnf:${record.tnf}   ${String(payload,  Charsets.UTF_8)}   ${String(payload.sliceArray(1 until payload.size), Charsets.UTF_8)} ")
                }
            }
        }
        // 处理标签数据...
    }

    override fun onDestroy() {
        super.onDestroy()
        usbDeviceReceiver?.let {
            unregisterReceiver(it)
        }
    }
}
